﻿using Elastic.Clients.Elasticsearch;
using FlyingEye.Common;
using FlyingEye.Exceptions;
using System.Threading.Tasks;

namespace FlyingEye.Repositories
{
    public abstract class ElasticsearchRepositoryBase
    {
        protected readonly ElasticsearchClient ESClient;

        private bool? _hasIndex = null;

        public ElasticsearchRepositoryBase(ESClient es)
        {
            ESClient = es.Client;
        }

        public abstract string Index { get; }

        public async Task InsertAsync<TRecord>(TRecord record) where TRecord : class
        {
            _hasIndex ??= this.ESClient.Indices.Exists(this.Index).Exists;

            if (_hasIndex.Value == false)
            {
                await this.ESClient.Indices.CreateAsync(Index);
            }

            var response = await ESClient.IndexAsync(record, Index);

            if (!response.IsValidResponse)
            {
                throw new ElasticsearchInsertException($"Elasticsearch insert is failed. the record type is {record.GetType().FullName}.", response.TryGetOriginalException(out var exec) ? exec : null);
            }
        }
    }
}
